package es.us.lsi.aws.api.externalservices;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import es.us.lsi.aws.api.model.TwitterSocialAccount;

public class TwitterHelper implements ISocialNetwork {
	
	private TwitterSocialAccount acc;
	private Twitter twitter;
	private RequestToken requestToken;
	
	public TwitterHelper(TwitterSocialAccount acc)
	{
		this.acc = acc;
	}
	@Override
	public int post(String message) {

		// The factory instance is re-useable and thread safe.
//		Twitter twitter = TwitterFactory.getSingleton();
//		ConfigurationBuilder cBuilder = new ConfigurationBuilder();
//		cBuilder.setOAuthConsumerKey(acc.getToken());
//		cBuilder.setOAuthConsumerSecret(acc.getTokenSecret());
//		Configuration conf = cBuilder.build();
		TwitterFactory fact = new TwitterFactory();
		Twitter twitter = fact.getInstance();
		
		AccessToken accessToken = new AccessToken(acc.getToken(),acc.getTokenSecret());
		
		twitter.setOAuthConsumer(OAuthCredentials.twitterCK, OAuthCredentials.twitterCS);
		twitter.setOAuthAccessToken(accessToken);
		try {
			Status status = twitter.updateStatus(message);
			System.out.println("Successfully updated the status to ["
					+ status.getText() + "].");
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			System.err
					.println("Something went wrong trying to post an update in twitter..."+e.getMessage());
			e.printStackTrace();
			return -1;
		}
		return 1;
	}

	

	@Override
	public String startOAuthProcess() {
		// TODO Auto-generated method stub
		TwitterFactory fact = new TwitterFactory();
		Twitter twitter = fact.getInstance();
		twitter.setOAuthConsumer(OAuthCredentials.twitterCK,
				OAuthCredentials.twitterCS);
		RequestToken requestToken = null;
		try {
			requestToken = twitter
					.getOAuthRequestToken("http://mybufferapp.appspot.com/1/accounts/callbackurl/twitter");
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err
					.println("Something went wrong trying get the access token URL");
		}
		this.twitter = twitter;
		this.requestToken = requestToken;
		return requestToken.getAuthorizationURL();
	}
	public Twitter getTwitter() {
		return twitter;
	}
	public RequestToken getRequestToken() {
		return requestToken;
	}
}
